import * as types from './action-types'
import {delay,takeEvery,put,take,all} from 'redux-saga/effects'

function* incrementAsync(): any{
  //yield后面可以跟一个promise,sagaMiddleware会停下来
  // ,等待这个promise变成成功态 才会继续向下执行
  yield delay(1000);

  yield put({type: types.INCREMENT})//store.dispatch({type: types.INCREMENT})
}

//saga就是一个generator函数
export function* watchAsyncIncrement(): any {
  //takeEvery是一个函数,接受两个参数。
  //+ 第一个是动作类型
  //+ 第二个是workerSaga
  //相当于向管理器发出了一个effect(指令对象) 告诉管理器我要干撒
  //【每当】收到types.ASYNC_INCREMENT,我都会执行incrementAsync
  yield takeEvery(types.ASYNC_INCREMENT, incrementAsync)
}

function* saga1(): any{
  console.log('saga1 before')
  yield take(types.INCREMENT) //等待派发动作 types.INCREMENT
  console.log('saga1 end')
}
function* saga2(): any{
  console.log('saga2 before')
  yield take(types.INCREMENT)
  console.log('saga2 before')
}

//如果yield了一个iterator,那么sagaMiddleware就会启动iterator自动执行
export default function* rootSaga(): any{

  console.log('rootSaga before')

  //1)
  /*saga执行顺序
        ↓ 下面只会输出saga1 before 然后就卡主了
    */
  // yield saga1()
  // yield saga2()

  // 要想并发执行↓
  // yield all([saga1(),saga2()]) //类似Promise.all

  yield all([watchAsyncIncrement()])

  console.log('rootSaga after')
}
